package taller2.controller.modes;

import java.awt.event.MouseEvent;

import javax.swing.JOptionPane;

import taller2.interfaces.Connection;
import taller2.interfaces.Graph;
import taller2.interfaces.Node;
import taller2.utils.Constants;
import taller2.utils.Point;
import taller2.utils.Utils;
import taller2.view.draws.DrawingArea;
import taller2.view.draws.GraphDrawer;

public class ChangeUseMode implements Mode{
	private Graph graph;
	
	// constructor
	public ChangeUseMode(Graph graph){
		this.graph = graph;
	}	
	
	// pressing the mouse button checks if there is a Node close enough
	// and selects it, to start moving it (but only if no other one is selected)
	public void whenPressed(MouseEvent arg0,DrawingArea area) {
		GraphDrawer drawer = area.getDrawer();
		Point pos = new Point(arg0.getX(),arg0.getY());
		
		if(drawer.noNodesSelected()){
			drawer.selectCloseByNode(pos);
		}else{
			int index1 = drawer.getSelectedNodeIndex();
			if(drawer.selectCloseByNode(pos)){
				int index2 = drawer.getSelectedNodeIndex();

				Node node1 = graph.getNodeByIndex(index1);				
				Node node2 = graph.getNodeByIndex(index2);

				Connection conn = node1.getConnectionTo(node2);
				
				node1.unselect();
				node2.unselect();

				if (conn != null){
				
					String use = JOptionPane.showInputDialog ("Enter node usage: "); 
			
					boolean NotEmpty = (use != null);
					boolean IsNumber = Utils.isANumber(use);
					if (NotEmpty&&IsNumber){
						int capacity = conn.getCapacity();
						int usage = Integer.valueOf(use);
						boolean IsValid = capacity >= usage;
						if(IsValid){
							conn.setCapacity(capacity);
							conn.setFlux(usage);
							conn.setWeight(Constants.ConnectionKilled);
						}
					}
				}				
			}
		}
		
		area.repaint();
	}

	public void whenReleased(MouseEvent arg0,DrawingArea area) {}

	public void whenDragged(MouseEvent arg0,DrawingArea area) {}
}
